import numpy as np
from ctypes import *
from interface.interface import Interface

class testfile:
    def __init__(self,c_temp_dir):
        self.fn = c_temp_dir + 'appdata'
        f = open(self.fn,'rb')
        self.d = (c_char * 4096)()
        f.readinto(self.d)
        f.close()

    def appData(self,types):
        addr = byref(self.d)
        vbuf = cast( addr, POINTER(types) )
        return vbuf.contents

    def close(self):
        f = open(self.fn,'wb')
        f.write(self.d)
        f.close()

class FileInterface(Interface):
    def __init__(self, fc, ran, filename):
        self.filename = filename
        self.ran = ran
        self.fc = fc
        ran.fc = fc
        ran.default_sample_rate = 1920000.0
        Interface.__init__(self,ran)

    def toFile(self,fn):
        self.reset()
        fs = self.getNearest()
        rfd = self.getRfData(fs,fn*self.fl)
        d = np.ctypeslib.as_array(rfd)
        d.tofile(self.filename)
    
    def toFileIQ(self,fn):
        self.reset()
        rfd,_ = self.getFrameData(0,fn*self.fl)
        wrd = np.zeros(rfd.shape,dtype=np.complex64)
        wrd[:] = rfd[:]
        wrd.tofile(self.filename)

    def fromFile(self):
        rfd = np.fromfile(self.filename,dtype=c_ubyte)
        start = int(self.data.frame_start_point)
        if start>self.fl:
            start = 0
            self.data.frame_start_point = 0
        return self.toIQ(rfd[start*2:],0)

    def prepare(self,fn):
        d = self.fromFile()
        len = d.shape[0]
        reqlen = (fn+1) * self.fl
        if reqlen<=len:
            return d[:reqlen]
        else:
            return d